package org.rockNarwhal.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.rockNarwhal.domain.User;
import org.rockNarwhal.service.PermissionService;
import org.rockNarwhal.service.RoleService;
import org.rockNarwhal.service.UserService;
import org.rockNarwhal.util.EncodeUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class DatabaseRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("用户通过验证...");
        //能进入到这里，表示账号已经通过验证了
        String userName =(String) principalCollection.getPrimaryPrincipal();
        //通过service获取角色和权限
        Set<String> permissions = permissionService.listPermissions(userName);
        Set<String> roles = roleService.listRoles(userName);
        System.out.println("用户角色:"+roles.toString());
        System.out.println("用户权限:"+permissions.toString());
        //授权对象
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        //把通过service获取到的角色和权限放进去
        s.setStringPermissions(permissions);
        s.setRoles(roles);
        return s;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("用户登陆验证...");
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        String username=token.getPrincipal().toString();
        String password=new String(token.getPassword());


        User user=userService.getUser(username);
        if (user == null) {
            System.out.println("用户不存在");
            throw new AuthenticationException();
        }
        String DBPassword=user.getPassword();

        String encodePassword= EncodeUtil.getEncodePassword(password,user.getSalt(),EncodeUtil.algorithmName,EncodeUtil.hashIterations);
        if(DBPassword==null||!DBPassword.equals(encodePassword)){
            System.out.println("DBPassword:"+DBPassword);
            System.out.println("encodePassword:"+encodePassword);
            throw new AuthenticationException();
        }
        return new SimpleAuthenticationInfo(username,password,getName());
    }
}
